$(function () {
    initEditor()
    getCateList()

    let state = '已发布'
    $('.btn-pub').click(function () {
        state = '已发布'
    })
    $('.btn-sold').click(function () {
        state = '草稿'
    })
    function getCateList() {
        axios({
            method: 'GET',
            url: '/my/cate/list'
        }).then(function (res) {
            if (res.data.code !== 0) {
                return layui.layer.msg('分类数据获取失败')
            }
            var list = []
            res.data.data.forEach(function (item) {
                list.push(`
                    <option value="${item.id}">${item.cate_name}</option>
                `)
            })
            $('#selectCate').append(list)
            layui.form.render('select')
        })
    }

    $('.btn-choose-img').click(function () {
        $('#file').click()
    })

    let file = null
    $('#file').on('change', function (e) {
        const files = e.target.files
        if (files.length === 0) {
            return file = null
        }
        file = files[0]
        const imgURL = URL.createObjectURL(files[0])
        $('#image').prop('src', imgURL)
    })

    var PhoneId = getQuery('id')
    if (PhoneId) {
        axios({
            method: 'GET',
            url: '/my/article/info',
            params: {
                id: PhoneId
            }
        }).then(function (res) {
            if (res.data.code !== 0) {
                return layui.msg('文章数据获取失败')
            }

            var { title, cate_id, cover_img, content, id } = res.data.data

            layui.form.val("phone-edit", {
                "cate_id": cate_id,
                "title": title,
                "content": content,
                "id": id
            })

            $('#image').prop('src', `http://www.liulongbin.top:3008${cover_img}`)

            layui.form.render()
        })
    }

    $('#Ph_pub').on('submit', function (e) {
        e.preventDefault()
        if (!file) {
            return layui.layer.msg('请选择封面后发布')
        }
        const fd = new FormData()
        fd.append('title', $('#title').val())
        fd.append('cate_id', $('#selectCate').val())
        fd.append('content', $('#content').val())
        fd.append('state', state)
        fd.append('cover_img', file)
        if (!PhoneId) {
            axios({
                method: 'POST',
                url: '/my/article/add',
                data: fd
            }).then(function (res) {
                if (res.data.code !== 0) {
                    return layui.layer.msg('手机发布失败')
                }
                layui.layer.msg('手机发布成功')
                location.href = '/Phone/Phlist.html'
                window.parent.highlight('手机列表')
            })
        } else {

        }

    })

})
function getQuery(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)")
    var r = window.location.search.substr(1).match(reg)
    if (r != null) return unescape(r[2])
    return null
}